﻿//------------------------------------------------------------------------------
// System Name:   Customer Service Platform
// Component:     CIS Domestic CompanyInfo
// Created By:    Samara Jiang (samaraj@wicresoft.com)
// Created Date:  2011-1-27
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASB.CC.Business.CIS;
using ASBCC.Business;
using ASBCC.Business.CIS;
using ASBCC.Database.EntityFramework;
using Wicresoft.Web.Controls;

namespace BEGDC.CC.Web.CIS2.Domestic
{
    /// <summary>
    ///  CIS Domestic CompanyInfo
    /// </summary>
    public partial class CompanyInfo : EntityPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                string companyID = Request.QueryString["view"];
                if (!String.IsNullOrEmpty(companyID))
                {
                    dvCompany.ChangeMode(DetailsViewMode.ReadOnly);
                    CurrentMode = EntityMode.Detail;
                }
            }
        }


        private UserRoles LoadRoles()
        {
            UserRoles right = CompanyInfoHelper.GetUserRightByRoleIDs((this.User as CSPrincipal).Role2s);
            if (!right.IsDomesticAdmin && right.IsDomesticSales && (User as CSPrincipal).AccessLevel == AccessLevel.Write)
                right.IsDomesticCommercial = true;
            return right;
        }



        protected override EntityDataSource EntitySource
        {
            get { return this.edsCompany; }
        }

        protected override Panel GridPanel
        {
            get
            {
                return CriteriaPanel;
            }
        }

        protected override TextBox EntitySearchTxt
        {
            get { return this.SearchText; }
        }

        protected override Button EntityAddBtn
        {
            get { return this.BtnAdd; }
        }

        protected override Button EntitySearchBtn
        {
            get { return this.Searchbtn; }
        }

        protected override Button EntityClearBtn
        {
            get { return this.Cleanbtn; }
        }

        protected override GridView EntityGrid
        {
            get { return this.gvCompany; }
        }

        protected override DetailsView EntityDetails
        {
            get { return this.dvCompany; }
        }

        protected override void OnEntityDisabling(int entityKey)
        {

            if (!CompanyInfoHelper.SetCompanyInfoDisabled(entityKey))
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript'>alert('" + Resources.Messages.DeleteCompanyFailedTips + "');</script>");
            GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.CID, "Company disabled. id=" + entityKey + "; name=" + CompanyManagementHelper.getName(entityKey));
        }

        protected override string GetEntityWhereExpression(string keyword)
        {

            //var filter = "it.Name like N'%" + keyword + "%'";

            //filter += (" and (it.CompanyID in {" + CustomerManageHelper.GetCompanyByRoleID((this.User as CSPrincipal).Role2String) + "})");
            
            string roles = (User as CSPrincipal).Role2String;
            UserRoles ur = LoadRoles();

            string companyWhere = "it.Name like N'%" + keyword + "%' and !it.Disabled ";
            companyWhere += " and ((Count( select value pc.Province.ProvinceID from it.PCATs as pc where !pc.Province.Disabled and !pc.Category.Disabled and ";
            companyWhere += string.Format("Count( select value r.RoleID from pc.Roles as r where !r.Disabled and r.RoleID in {{{0}}} ) > 0 ) > 0 )", roles);
            if (ur.IsDomesticAdmin)
            {
                companyWhere += " or Count( select value pc.Province.ProvinceID from it.PCATs as pc where !pc.Province.Disabled and !pc.Category.Disabled ) > 0";
            }
            companyWhere += " ) ";

            var cid = this.Request.QueryString["CID"];
            if (cid != null)
            {
                if (cid != "")
                    companyWhere += " and it.CompanyID in { " + cid + " }";
                else
                    companyWhere += " and it.CompanyID in { 0 }";
            }
            string companyID = Request.QueryString["view"];
            if (!String.IsNullOrEmpty(companyID))
            {
                edsCompany.Where = "it.CompanyID == " + companyID;
                edsCompany.DataBind();
            }
            return companyWhere;
        }

        protected override void OnEntityInserting(EntityDataSourceChangingEventArgs e)
        {
            var dc = e.Context;
            var company = e.Entity as Company;
            company.Name = this.Request.Form["company-name"].Trim();
            IPrincipal user = (IPrincipal)(Context.User);
            CompanyInfoHelper.OnCompanyInfoInserting(dc, company, user);
            UserRoles userRole = LoadRoles();
            if (userRole.IsDomesticSales && !userRole.IsDomesticAdmin)
            {
                string value = this.Request.Form["ReturnValue"];
                CompanyInfoHelper.OnCompanyWithPCATInserting(dc, company, value);
            }
            if (userRole.IsDomesticAdmin)
            {
                string value1 = this.Request.Form["SelectP"];
                string value2 = this.Request.Form["SelectC"];
                CompanyInfoHelper.OnCompanyWithPCATInserting(dc, company, value1 + ";" + value2);
            }
            if (userRole.IsOverseaSales)
            {
                string value = this.Request.Form["ReturnCountry"];
                value = value == "" || value == null ? "0" : value;
                CompanyInfoHelper.OnCompanyWithCountryInserting(dc, company, value);
            }

        }

        protected override void OnEntityUpdating(EntityDataSourceChangingEventArgs e)
        {
            var dc = e.Context;
            var company = e.Entity as Company;
            company.Name = this.Request.Form["company-name"].Trim();
            IPrincipal user = (IPrincipal)(Context.User);
            company.CreateByReference.Load();
            CompanyInfoHelper.OnCompanyInfoUpdating(dc, company, user);
            UserRoles userRole = LoadRoles();
            if (userRole.IsDomesticSales && !userRole.IsDomesticAdmin)
            {
                string value = this.Request.Form["ReturnValue"];
                CompanyInfoHelper.OnCompanyWithPCATUpdating(dc, company, value);
            }
            if (userRole.IsDomesticAdmin)
            {
                string value1 = this.Request.Form["SelectP"];
                string value2 = this.Request.Form["SelectC"];
                CompanyInfoHelper.OnCompanyWithPCATUpdating(dc, company, value1 + ";" + value2);
            }
            if (userRole.IsOverseaSales)
            {
                string value = this.Request.Form["ReturnCountry"];
                value = value == "" || value == null ? "0" : value;
                CompanyInfoHelper.OnCompanyWithCountryUpdating(dc, company, value);
            }
            
        }


        protected IEnumerable GetPCATs(object rawPCATs)
        {
            foreach (var pcat in rawPCATs as IEnumerable<PCAT>)
            {
                pcat.CategoryReference.Load();
                pcat.ProvinceReference.Load();
                yield return pcat;
            }
        }


        protected IEnumerable GetCountries(object rawCountries)
        {
            foreach (var country in rawCountries as IEnumerable<Country>)
            {
                country.Areas.Load();
                yield return country;
            }
        }

        /// <summary>
        /// 通过当前用户的roles取PCAT
        /// </summary>
        protected IEnumerable GetManagedPCATList(int companyID)
        {
            return CompanyInfoHelper.GetManagedPCATList((this.User as CSPrincipal).Role2s, (this.User as CSPrincipal).Role2String, companyID);
        }

        /// <summary>
        /// 创建Company时通过当前用户的roles取PCAT
        /// </summary>
        protected IEnumerable GetManagedPCATListWhenInserting()
        {
            return CompanyInfoHelper.GetManagedPCATListWhenInserting(LoadRoles(), (this.User as CSPrincipal).Role2s, (this.User as CSPrincipal).Role2String);
        }

        /// <summary>
        /// 通过当前用户的roles取Country
        /// </summary>
        protected IEnumerable GetManagedCountryList(string companyID)
        {
            return CompanyInfoHelper.GetManagedCountryList((this.User as CSPrincipal).Role2s, (this.User as CSPrincipal).Role2String, int.Parse(companyID));
        }

        protected void edsCompany_Inserted(object sender, EntityDataSourceChangedEventArgs e)
        {

            var dc = e.Context;
            var company = e.Entity as Company;
            var address = LogInfoHelper.GetAddressC(company.Address);
            var tel = LogInfoHelper.GetTelephoneC(company.Tel);
            var fax = LogInfoHelper.GetFaxC(company.Fax);
            var website = LogInfoHelper.GetWebsiteC(company.Website);
            var zip = LogInfoHelper.GetAddressC(company.Zip);
            string value1 = this.Request.Form["SelectP"];
            string value2 = this.Request.Form["SelectC"];
            var province = LogInfoHelper.GetProvinceC(value1);
            var cat = LogInfoHelper.GetCATC(value2);

            GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.CID, "Company inserted. id=" + company.CompanyID + "; name=" + company.Name + address + tel + fax + website + zip + province + cat);


        }


        protected void edsCompany_Updated(object sender, EntityDataSourceChangedEventArgs e)
        {
            var dc = e.Context;
            var company = e.Entity as Company;
            var address = LogInfoHelper.GetAddressC(company.Address);
            var tel = LogInfoHelper.GetTelephoneC(company.Tel);
            var fax = LogInfoHelper.GetFaxC(company.Fax);
            var website = LogInfoHelper.GetWebsiteC(company.Website);
            var zip = LogInfoHelper.GetAddressC(company.Zip);
            string value1 = this.Request.Form["SelectP"];
            string value2 = this.Request.Form["SelectC"];
            var province = LogInfoHelper.GetProvinceC(value1);
            var cat = LogInfoHelper.GetCATC(value2);

            GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.CID, "Company updated. id=" + company.CompanyID + "; name=" + company.Name + address + tel + fax + website + zip + province + cat);


        }


        protected string GetProvince(object CompanyID)
        {
            return CompanyInfoHelper.GetProvinceNameByCompanyID(int.Parse(CompanyID.ToString()));
        }


        /// <summary>
        /// 通过countryID取Area
        /// </summary>
        protected IEnumerable GetAreas(object dataItem)
        {
            var country = dataItem as Country;
            country.Areas.Load();
            return country.Areas.Where(p => !p.Disabled);
        }

        protected override void OnEntityAuthorize(EntityMode mode, IEnumerable<DataControlField> fields)
        {
            // 如果当前是只读状态，则跳过鉴权
            //if (EntityDetails.CurrentMode == DetailsViewMode.ReadOnly)
            //    return;

            //var role = GetCurrentRole();

            var userRoles = LoadRoles();

            if (mode == EntityMode.Grid)
            {
                fields.First(p => p.AccessibleHeaderText == "gvZip").Visible = userRoles.IsDomesticSales;
                fields.First(p => p.AccessibleHeaderText == "gvPCATs").Visible = userRoles.IsDomesticSales;
                if (userRoles.IsDomesticCommercial && !userRoles.IsDomesticAdmin)
                {
                    var actionField = EntityGrid.Columns.Cast<DataControlField>().First(p => p is ActionField) as ActionField;
                    actionField.ShowDisableButton = false;
                }
            }
            else
            {

                // 首先把列全部隐藏
                foreach (var field in fields)
                {
                    field.Visible = false;
                }

                // 然后根据权限一点一点显示出来
                fields.First(p => p.AccessibleHeaderText == "Address").Visible = true;
                fields.First(p => p.AccessibleHeaderText == "Tel").Visible = true;
                fields.First(p => p.AccessibleHeaderText == "Fax").Visible = true;
                fields.First(p => p.AccessibleHeaderText == "Website").Visible = true;
                fields.First(p => p.AccessibleHeaderText == "Zip").Visible = true;
                fields.First(p => p.AccessibleHeaderText == "LastModifyBy").Visible = true;
                //if (userRoles.IsOverseaAdmin || userRoles.IsDomesticAdmin || userRoles.IsDomesticCommercial)
                if ((this.User as CSPrincipal).AccessLevel == AccessLevel.Write && EntityDetails.CurrentMode == DetailsViewMode.ReadOnly)
                    fields.First(p => p.AccessibleHeaderText == "AddCustomer").Visible = true;
                if (userRoles.IsDomesticSales)
                {
                    if (userRoles.IsDomesticCommercial && !userRoles.IsDomesticAdmin)
                    {
                        if (EntityDetails.CurrentMode != DetailsViewMode.Insert)
                        {
                            fields.First(p => p.AccessibleHeaderText == "CompanyNameReadOnly").Visible = true;
                        }
                        else
                        {
                            fields.First(p => p.AccessibleHeaderText == "CompanyName").Visible = true;
                        }
                        if (EntityDetails.CurrentMode != DetailsViewMode.Edit)
                        {
                            fields.First(p => p.AccessibleHeaderText == "PCATs").Visible = true;
                        }
                    }
                    //if (userRoles.IsOverseaAdmin || userRoles.IsDomesticAdmin)
                    else
                    {
                        fields.First(p => p.AccessibleHeaderText == "CompanyName").Visible = true;
                        fields.First(p => p.AccessibleHeaderText == "PCATs").Visible = true;
                    }
                }
               
                if (userRoles.IsDomesticAdmin)
                {
                    IsDomenticAdmin = "yes";
                }
                else if (userRoles.IsDomesticSales)
                {
                    IsDomenticAdmin = "no";
                }



            }
        }

        protected string IsDomenticAdmin;

        protected string GetOCString()
        {
            if (IsPostBack)
            {

                var companyID = this.dvCompany.DataKey.Value;
                if (companyID != null)
                    return CustomerOCHelper.GetOCString((int)companyID);
            }
            return "[]";
        }


        protected string GetCustomerByCompanyID(int companyID)
        {
            return CompanyInfoHelper.GetCustomerIDsByCompanyID(companyID);
        }

        protected string CheckOCShow(int companyID)
        {
            return CompanyInfoHelper.GetBelongsToByCompanyID(companyID) ? "inline" : "none";
        }
        protected void ddlArea_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var area = sender as DropDownList;
                area.DataSource = new[] { "All", "Domestic", "Oversea" };
                area.DataBind();
            }
        }
        protected string GetUser()
        {
            string userName = this.User.Identity.Name;
            return userName;
        }

        protected string GetProvince(int companyID)
        {
            return CompanyInfoHelper.GetProvinceIDByCompanyID(companyID).ToString();
        }

        protected string GetCategory(int companyID)
        {
            return CompanyInfoHelper.GetCateIDByCompanyID(companyID).ToString();
        }

        protected IEnumerable GetProvinces()
        {
            return CompanyInfoHelper.GetProvince();
        }

        protected IEnumerable GetCategories()
        {
            return CompanyInfoHelper.GetCategory();
        }

        protected int GetCountryIDByCompanyID(int companyID)
        {
            return CompanyInfoHelper.GetCountryIDByCompanyID(companyID);
        }

        protected IEnumerable GetCountries()
        {
            return CompanyInfoHelper.GetCountryByRoleID((User as CSPrincipal).Role2s);
        }

        protected string GetAreaByCountryID(int countryID)
        {
            return CompanyInfoHelper.GetAreaByCountryID(countryID);
        }

        protected string GetRoleIDs()
        {
            string roles = (User as CSPrincipal).Role2String;
            return roles;
        }

        [WebMethod]
        public static string CheckCompanyName(string name, string roles)
        {
            return CompanyInfoHelper.CheckCompanyName(name, roles) ? "0" : "1";
        }

    }




}
